package com.coocaa.cirrus.common.base.util;

import com.alibaba.fastjson.JSON;
import com.coocaa.cirrus.common.base.model.MetaDataModel;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.GpsDirectory;
import com.qcloud.cos.model.ObjectMetadata;

import java.io.File;
import java.io.IOException;

/**
 * @author bijiahao
 * @date : 2025/9/16 18:29
 * @description
 */
public class MetaDataParseUtil {


    public static ObjectMetadata parseObjectMetadata(File file) {
        MetaDataModel metaDataModel = MetaDataParseUtil.parseMetaData(file);
        if (null == metaDataModel) {
            return null;
        }
        ObjectMetadata ossMeta = new ObjectMetadata();
        // 存储拍摄时间
        ossMeta.addUserMetadata("x-oss-meta-shoottime", metaDataModel.getShootTime());
        if (null != metaDataModel.getLocation()) {
            // 存储拍摄地点
            ossMeta.addUserMetadata("x-oss-meta-location", metaDataModel.getLocation());
        }
        return ossMeta;
    }

    public static MetaDataModel parseMetaData(File file) {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(file);
            ExifSubIFDDirectory exifDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            // 拍摄时间
            String shootTime = exifDir.getString(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
            GpsDirectory gpsDir = metadata.getFirstDirectoryOfType(GpsDirectory.class);
            // 拍摄地点
            String location = gpsDir != null ? gpsDir.getGeoLocation().toString() : null;
            MetaDataModel res = MetaDataModel.builder()
                    .shootTime(shootTime)
                    .location(location)
                    .build();
            return res;
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String p = "/Users/bijiahao/Downloads/20250904-161914.jpeg";
        MetaDataModel res = parseMetaData(new File(p));
        System.out.println(JSON.toJSONString(res));
    }
}
